//
//  JZCameraViewController.m
//  JZShortVideo
//
//  Created by liujz on 31/05/2018.
//  Copyright © 2018 liujz. All rights reserved.
//

#define kScreenWidth        [UIScreen mainScreen].bounds.size.width
#define kScreenHeight       [UIScreen mainScreen].bounds.size.height
#define IS_IPHONE_X         ((IS_IPHONE && kScreenHeight == 812.0)? YES : NO)
#define IS_IPHONE           (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define NavHFit             (IS_IPHONE_X ? 88 : 64)
#define BottomYFit          (IS_IPHONE_X ? 43 : 0)
#define WeakObj(o) @autoreleasepool{} __weak typeof(o) o##Weak = o;
#define TOOL_BAR_HEIGHT 150.0f

#import "JZCameraViewController.h"
#import "JZPreviewPlayerController.h"
#import "JZCameraShootingToolBar.h"
#import "ColorManager.h"
#import <Photos/Photos.h>
#import <Masonry/Masonry.h>

typedef void(^PropertyChangeBlock)(AVCaptureDevice *captureDevice);

@interface JZCameraViewController () <ShootingToolBarDelegate, AVCaptureFileOutputRecordingDelegate>

// 拍摄条
@property (nonatomic, strong)   JZCameraShootingToolBar     *toolBar;
// 播放VC
@property (nonatomic, strong)   JZPreviewPlayerController   *previewPlayerVC;
// 显示视频的内容
@property (nonatomic, strong)   UIView                      *userCamera;
// 负责输入和输出设置之间的数据传递
@property (nonatomic, strong)   AVCaptureSession            *captureSession;
// 负责从AVCaptureDevice获得输入数据
@property (nonatomic, strong)   AVCaptureDeviceInput        *captureDeviceInput;
// 照片输出流
@property (nonatomic, strong)   AVCaptureStillImageOutput   *captureStillImageOutput;
// 视频输出流
@property (nonatomic, strong)   AVCaptureMovieFileOutput    *captureMovieFileOutput;
// 相机拍摄预览图层
@property (nonatomic, strong)   AVCaptureVideoPreviewLayer  *captureVideoPreviewLayer;
// 后台任务标示符
@property (nonatomic, assign)   UIBackgroundTaskIdentifier  backgroundTaskIdentifier;
// 保存的Url
@property (nonatomic, strong)   NSURL       *localMovieUrl;
// 拍照的照片
@property (nonatomic, strong)   UIImage     *imagePhoto;
// 是否对焦
@property (nonatomic, assign)   BOOL        isFocus;
// 聚焦光标
@property (nonatomic, strong)   UIImageView *focusCursor;
// 记录开始的缩放比例
@property (nonatomic, assign)   CGFloat     beginGestureScale;
// 最后的缩放比例
@property (nonatomic, assign)   CGFloat     effectiveScale;
// 切换摄像头
@property (nonatomic, strong)   UIButton    *switchCameraBtn;
// 轻触拍照，按住摄像
@property (nonatomic, strong)   UILabel     *lblTipTitle;

@end


@implementation JZCameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupSubViews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.captureSession startRunning];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.captureSession stopRunning];
}

- (void)dealloc {
    // Camera ViewController destroied
}

/**
 设置添加子控件
 */
- (void)setupSubViews {
    
    [self.view addSubview:self.userCamera];
    
    [self.view addSubview:self.toolBar];
    
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(TOOL_BAR_HEIGHT));
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    [self.view addSubview:self.switchCameraBtn];
    
    // Show tips when shoot short video
    if (self.type & JZCameraTypeShortVideo) {
        
        self.lblTipTitle.center = CGPointMake(self.toolBar.center.x, self.toolBar.center.y - 60.0f);
        [self.view addSubview:self.lblTipTitle];
        
        self.lblTipTitle.alpha = 1.0f;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:1.0 animations:^{
                self.lblTipTitle.alpha = 0.0f;
            }];
        });
    }
    
    [self addChildViewController:self.previewPlayerVC];
    
    self.focusCursor = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"focus_rect" inBundle:CAMERA_CURRENT_BUNDLE compatibleWithTraitCollection:nil]];
    [self.view addSubview:self.focusCursor];
    [self hiddenFocusCursorAction];
    
    self.beginGestureScale  = 1.0f;
    self.effectiveScale     = 1.0f;
    
    [self addGenstureRecognizer];
    
    [self settingUserCamera];
}

#pragma mark - Notification Action

/**
 *  捕获区域改变
 *
 *  @param notification 通知对象
 */
- (void)areaChange:(NSNotification *)notification {
    // 捕获区域改变
}

/**
 *  Switch Camera 切换摄像头
 */
- (void)switchCamera {
    
    [self.captureSession beginConfiguration];
    [self.captureSession removeInput:self.captureDeviceInput];
    AVCaptureDevice *swithToDevice = [self getSwitchCameraDevice];
    
    [swithToDevice lockForConfiguration:nil];
    
    [self setExposureModeWithDevice:swithToDevice];
    self.captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:swithToDevice error:nil];
    [_captureSession addInput:_captureDeviceInput];
    [_captureSession commitConfiguration];
    
}

- (AVCaptureDevice *)getSwitchCameraDevice {
    
    AVCaptureDevice *currentDevice = [self.captureDeviceInput device];
    AVCaptureDevicePosition currentPosition = [currentDevice position];
    
    BOOL isUnspecifiedOrFront = (currentPosition == AVCaptureDevicePositionUnspecified || currentPosition == AVCaptureDevicePositionFront);
    
    AVCaptureDevicePosition swithToPosition = isUnspecifiedOrFront ? AVCaptureDevicePositionBack : AVCaptureDevicePositionFront;
    
    NSArray *cameras = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    __block AVCaptureDevice *swithCameraDevice = nil;
    [cameras enumerateObjectsUsingBlock:^(AVCaptureDevice *camera, NSUInteger idx, BOOL * _Nonnull stop) {
        if(camera.position == swithToPosition) {
            swithCameraDevice = camera;
            *stop = YES;
        }
    }];
    
    return swithCameraDevice;
}

/**
 *  Exposure Mode 配置曝光模式
 */
- (void)setExposureModeWithDevice:(AVCaptureDevice *)device {
    NSError *error = nil;
    // 注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁
    [device lockForConfiguration:&error];
    // 设置持续曝光模式
    if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
        [device setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
    }
    [device unlockForConfiguration];
}

#pragma mark - AVCaptureFileOutputRecordingDelegate

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections {
    // 开始录制
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error {
    // 完成录制
}

#pragma mark - ShootingToolBar Delegate Methods

- (void)shooingStart:(JZCameraShootingToolBar *)toolBar actionType:(ActionType)actionType progress:(CGFloat)value {
    
    if (Photo == actionType) {
        // 拍照开始
    } else if (Video == actionType) {
        // 视频开始
        [self startRecordVideo];
    }
    
}

- (void)shootingStop:(JZCameraShootingToolBar *)toolBar shootingType:(ActionType)actionType {
    // 取出播放视图
    JZPreviewPlayerController* vc = self.childViewControllers[0];
    [self.view insertSubview:vc.view aboveSubview:self.userCamera];
    if (Photo == actionType) {
        // 拍照结束
        [self takePhoto:vc];
    } else if (Video == actionType) {
        // 视频结束
        [self stopRecordVideo];
        vc.url = self.localMovieUrl;
    }
}

- (void)shootingToolBarAction:(JZCameraShootingToolBar *)toolBar buttonIndex:(NSInteger)index {
    
    if (1 == index) {   // 取消
        // 重新拍摄
        [self.captureSession startRunning];
        [self.previewPlayerVC removeSubViews];
        [self.previewPlayerVC.player pause];
    }  else if (3 == index) {   // 关闭
        if (self.shootFinished) {
            self.shootFinished(NO, nil, nil);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    } else if (4 == index) {    // 确定
        if (self.shootFinished) {
            self.shootFinished(YES, self.imagePhoto, self.localMovieUrl);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}

#pragma mark - Property Methods

/**
 用来显示录像内容
 
 @return UIView
 */
- (UIView *)userCamera
{
    if (!_userCamera) {
        _userCamera = [[UIView alloc] initWithFrame:self.view.bounds];
        _userCamera.backgroundColor = [UIColor blackColor];
        
    }
    return _userCamera;
}

/**
 设置摄像头
 
 @return BOOL 是否设置成功
 */
- (BOOL)settingUserCamera {
    //初始化会话
    _captureSession = [[AVCaptureSession alloc] init];
    if (@available(iOS 9.0, *)) {
        if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset3840x2160]) {
            //设置分辨率
            _captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
        }
    } else {
        // Fallback on earlier versions
        _captureSession.sessionPreset = AVCaptureSessionPreset1920x1080;
    }
    
    // 获得视频输入设备
    
    AVCaptureDevicePosition defaultDevicePos = AVCaptureDevicePositionBack; // 后置
    if (self.type & JZCameraTypeSelfie) {  // 自拍
        defaultDevicePos = AVCaptureDevicePositionFront; // 前置
    }
    AVCaptureDevice *videoCaptureDevice = [self getCameraDeviceWithPosition:defaultDevicePos]; // 取得摄像头
    if (!videoCaptureDevice) {
        NSLog(@"取得摄像头时出现问题.");
        return NO;
    }
    
    //添加一个音频输入设备
    AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    
    //根据输入设备初始化设备输入对象，用于获得输入数据
    NSError *error = nil;
    _captureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:videoCaptureDevice error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错，错误原因：%@", error.localizedDescription);
        return NO;
    }
    
    AVCaptureDeviceInput *audioCaptureDeviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:audioCaptureDevice error:&error];
    if (error) {
        NSLog(@"取得设备输入对象时出错，错误原因：%@", error.localizedDescription);
        return NO;
    }
    
    // 初始化设备输出对象，用于获得输出数据
    _captureMovieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
    
    // 将设备输入添加到会话中
    if ([_captureSession canAddInput:_captureDeviceInput]) {
        [_captureSession addInput:_captureDeviceInput];
        [_captureSession addInput:audioCaptureDeviceInput];
        AVCaptureConnection *captureConnection = [_captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
        if ([captureConnection isVideoStabilizationSupported]) {
            captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
        }
    }
    
    // 将设备输出添加到会话中
    if ([_captureSession canAddOutput:_captureMovieFileOutput]) {
        [_captureSession addOutput:_captureMovieFileOutput];
    }
    
    // 照片输出
    _captureStillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [_captureStillImageOutput setOutputSettings:outputSettings];    // 输出设置
    // 将设备输出添加到会话中
    if ([_captureSession canAddOutput:_captureStillImageOutput]) {
        [_captureSession addOutput:_captureStillImageOutput];
    }
    
    // 创建视频预览层，用于实时展示摄像头状态
    _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.captureSession];
    
    CALayer *layer = self.userCamera.layer;
    layer.masksToBounds = YES;
    
    _captureVideoPreviewLayer.frame = layer.bounds;
    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; // 填充模式
    // 将视频预览层添加到界面中
    [layer addSublayer:_captureVideoPreviewLayer];
    
    return YES;
}

/**
 *  取得指定位置的摄像头
 *
 *  @param position 摄像头位置
 *
 *  @return 摄像头设备
 */
- (AVCaptureDevice *)getCameraDeviceWithPosition:(AVCaptureDevicePosition)position {
    
    if (@available(iOS 10.0, *)) {
        AVCaptureDeviceDiscoverySession *devicesIOS10 = [AVCaptureDeviceDiscoverySession  discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:position];
        
        NSArray *devicesIOS = devicesIOS10.devices;
        for (AVCaptureDevice *device in devicesIOS) {
            if ([device position] == position) {
                return device;
            }
        }
        return nil;
        
    } else {
        // Fallback on earlier versions
        NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
        
        //遍历这些设备返回跟postion相关的设备
        for (AVCaptureDevice *device in devices) {
            if ([device position] == position) {
                return device;
            }
        }
        return nil;
    }
    
}

// 开始录制视频
- (void)startRecordVideo {
    
    AVCaptureConnection *connection = [self.captureMovieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    
    if (![self.captureSession isRunning]) {
        // 如果捕获会话没有运行
        [self.captureSession startRunning];
    }
    
    // 根据连接取得设备输出的数据
    if (![self.captureMovieFileOutput isRecording]) { //如果输出 没有录制
        
        // 如果支持多任务则则开始多任务
        if ([[UIDevice currentDevice] isMultitaskingSupported]) {
            self.backgroundTaskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
            [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
        }
        
        // 预览图层和视频方向保持一致
        connection.videoOrientation = [self.captureVideoPreviewLayer connection].videoOrientation;
        
        //开始录制视频使用到了代理 AVCaptureFileOutputRecordingDelegate 同时还有录制视频保存的文件地址的
        [self.captureMovieFileOutput startRecordingToOutputFileURL:self.localMovieUrl recordingDelegate:self];
    }
    
}

// 停止录制视频
- (void)stopRecordVideo {
    
    if ([self.captureMovieFileOutput isRecording]) {
        [self.captureMovieFileOutput stopRecording];
    }
    // 把捕获会话也停止的话，预览视图就停了
    if ([self.captureSession isRunning]) {
        [self.captureSession stopRunning];
    }
}

// 开始拍照
- (void)takePhoto:(JZPreviewPlayerController *)vc {
    //根据设备输出获得连接
    AVCaptureConnection *captureConnection = [self.captureStillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    
    //根据连接取得设备输出的数据
    WeakObj(self);
    [self.captureStillImageOutput captureStillImageAsynchronouslyFromConnection:captureConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer) {
            
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            
            if (selfWeak.captureDeviceInput && selfWeak.captureDeviceInput.device && AVCaptureDevicePositionFront == selfWeak.captureDeviceInput.device.position) {
                UIImage* mirrorImage = [UIImage imageWithCGImage:image.CGImage scale:1.0 orientation:UIImageOrientationLeftMirrored];
                if (mirrorImage) {
                    image = mirrorImage;
                }
            }
            
            selfWeak.imagePhoto = image;
            vc.image = image;
        }
    }];
}

/**
 *  改变设备属性的统一操作方法
 *
 *  @param propertyChange 属性改变操作
 */
- (void)changeDeviceProperty:(PropertyChangeBlock)propertyChange {
    AVCaptureDevice *captureDevice = [self.captureDeviceInput device];
    NSError *error;
    // 注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁
    if ([captureDevice lockForConfiguration:&error]) {
        // 自动白平衡
        if ([captureDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
            [captureDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
        }
        // 自动根据环境条件开启闪光灯
        if ([captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [captureDevice setFlashMode:AVCaptureFlashModeAuto];
        }
        
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
    } else {
        NSLog(@"设置设备属性过程发生错误，错误信息：%@", error.localizedDescription);
    }
}

/**
 *  设置闪光灯模式
 *
 *  @param flashMode 闪光灯模式
 */
- (void)setFlashMode:(AVCaptureFlashMode)flashMode{
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFlashModeSupported:flashMode]) {
            [captureDevice setFlashMode:flashMode];
        }
    }];
}

/**
 *  设置聚焦模式
 *
 *  @param focusMode 聚焦模式
 */
- (void)setFocusMode:(AVCaptureFocusMode )focusMode {
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFocusModeSupported:focusMode]) {
            [captureDevice setFocusMode:focusMode];
        }
    }];
}

/**
 *  设置曝光模式
 *
 *  @param exposureMode 曝光模式
 */
- (void)setExposureMode:(AVCaptureExposureMode)exposureMode {
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isExposureModeSupported:exposureMode]) {
            [captureDevice setExposureMode:exposureMode];
        }
    }];
}

/**
 *  设置聚焦点
 *
 *  @param point 聚焦点
 */
- (void)focusWithMode:(AVCaptureFocusMode)focusMode exposureMode:(AVCaptureExposureMode)exposureMode atPoint:(CGPoint)point {
    
    [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
        if ([captureDevice isFocusPointOfInterestSupported]) {
            [captureDevice setFocusPointOfInterest:point];
        }
        if ([captureDevice isExposurePointOfInterestSupported]) {
            [captureDevice setExposurePointOfInterest:point];
        }
        if ([captureDevice isExposureModeSupported:exposureMode]) {
            [captureDevice setExposureMode:exposureMode];
        }
        if ([captureDevice isFocusModeSupported:focusMode]) {
            [captureDevice setFocusMode:focusMode];
        }
    }];
    
}

/**
 *  添加点按手势，点按时聚焦
 */
- (void)addGenstureRecognizer {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapScreen:)];
    [self.view addGestureRecognizer:tapGesture];
    
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    [self.view addGestureRecognizer:pinchGesture];
}

/**
 *  点按手势事件方法
 */
- (void)tapScreen:(UITapGestureRecognizer *)tapGesture {
    
    if ([self.captureSession isRunning]) {
        CGPoint point= [tapGesture locationInView:self.view];
        //将UI坐标转化为摄像头坐标
        CGPoint cameraPoint= [self.captureVideoPreviewLayer captureDevicePointOfInterestForPoint:point];
        [self setFocusCursorWithPoint:point];
        [self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposureMode:AVCaptureExposureModeContinuousAutoExposure atPoint:cameraPoint];
    }
    
}

/**
 *  设置聚焦光标位置
 *
 *  @param point 光标位置
 */
- (void)setFocusCursorWithPoint:(CGPoint)point {
    
    if (!self.isFocus) {
        self.isFocus = YES;
        self.focusCursor.center = point;
        self.focusCursor.transform = CGAffineTransformMakeScale(1.25, 1.25);
        self.focusCursor.alpha = 1.0;
        [UIView animateWithDuration:0.5 animations:^{
            self.focusCursor.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self performSelector:@selector(hiddenFocusCursorAction) withObject:nil afterDelay:0.5];
        }];
    }
}

- (void)hiddenFocusCursorAction {
    self.focusCursor.alpha = 0;
    self.isFocus = NO;
}


#pragma mark - GestureRecognizer delegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}

// 缩放手势 用于调整焦距
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer {
    BOOL touchAvaliad = YES;
    NSUInteger numTouches = [recognizer numberOfTouches];
    NSUInteger i;
    
    for (i = 0; i < numTouches; ++i) {
        CGPoint location = [recognizer locationOfTouch:i inView:self.view];
        CGPoint convertedLocation = [self.captureVideoPreviewLayer convertPoint:location fromLayer:self.captureVideoPreviewLayer.superlayer];
        
        if (![self.captureVideoPreviewLayer containsPoint:convertedLocation]) {
            touchAvaliad = NO;
            break;
        }
    }
    
    if (touchAvaliad) {
        CGFloat maxScaleAndCropFactor = 10.0f;
        
        CGFloat scaleWillChange = self.beginGestureScale;
        if (0.0f != recognizer.scale) {
            scaleWillChange = ((recognizer.scale >= 1.0f) ? (self.beginGestureScale + recognizer.scale / 15.0f) : (self.beginGestureScale - (1.0f / recognizer.scale) / 15.0f));
        }
        
        if (scaleWillChange >= 1.0f && scaleWillChange <= maxScaleAndCropFactor) {
            
            NSLog(@"Scale:%f", recognizer.scale);
            
            self.effectiveScale = scaleWillChange;
            [self updateVideoScaleAndCropFactor:self.effectiveScale];
            self.beginGestureScale = self.effectiveScale;
        }
    }
}

- (void)updateVideoScaleAndCropFactor:(CGFloat)scale {
    
    if (scale < self.captureDeviceInput.device.activeFormat.videoMaxZoomFactor && scale > 1) {
        [self changeDeviceProperty:^(AVCaptureDevice *captureDevice) {
            [captureDevice rampToVideoZoomFactor:scale withRate:10];
        }];
    }
    
}

// 设置视频保存地址
- (NSURL *)localMovieUrl
{
    if (_localMovieUrl == nil) {
        
        NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingString:@"shortVideo.mov"];
        
        NSURL *fileUrl = [NSURL fileURLWithPath:outputFilePath];
        
        _localMovieUrl = fileUrl;
    }
    
    return _localMovieUrl;
}

/**
 拍摄工具条
 
 @return ShootingToolBar
 */
- (JZCameraShootingToolBar *)toolBar {
    
    if (!_toolBar) {
        
        BOOL bTapEnable         = (self.type & JZCameraTypePhoto);
        BOOL bLongPressEnable   = (self.type & JZCameraTypeShortVideo);
        
        _toolBar = [[JZCameraShootingToolBar alloc] initWithFrame:CGRectMake(0, (kScreenHeight-TOOL_BAR_HEIGHT-BottomYFit), self.view.frame.size.width, TOOL_BAR_HEIGHT) TapEnable:bTapEnable LongPressEnable:bLongPressEnable];
        
        _toolBar.shootingToolBarDelegate = self;
        _toolBar.backgroundColor = [UIColor clearColor];
    }
    
    return _toolBar;
}

- (UILabel *)lblTipTitle {
    
    if (!_lblTipTitle) {
        _lblTipTitle = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 150.0f, 20.0f)];
        _lblTipTitle.backgroundColor = [UIColor clearColor];
        _lblTipTitle.text = @"轻触拍照，长按摄像";
        _lblTipTitle.textAlignment = NSTextAlignmentCenter;
        _lblTipTitle.textColor = [UIColor whiteColor];
        _lblTipTitle.font = [UIFont systemFontOfSize:14.0f];
        _lblTipTitle.shadowColor = [UIColor darkGrayColor];
        _lblTipTitle.shadowOffset = CGSizeMake(0.5f, 0.5f);
    }
    
    return _lblTipTitle;
}

/**
 切换摄像头按钮
 
 @return UIButton
 */
- (UIButton *)switchCameraBtn {
    if (!_switchCameraBtn) {
        _switchCameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_switchCameraBtn setImage:[UIImage imageNamed:@"camera_switch" inBundle:CAMERA_CURRENT_BUNDLE compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
        [_switchCameraBtn addTarget:self action:@selector(switchCamera) forControlEvents:UIControlEventTouchUpInside];
        _switchCameraBtn.frame = CGRectMake(kScreenWidth - 40.0f, 20.0f, 25.0f, 21.0f);
    }
    return _switchCameraBtn;
}

/**
 展示PreviewController
 
 @return IdsCameraPreviewController
 */
- (JZPreviewPlayerController *)previewPlayerVC
{
    if (!_previewPlayerVC) {
        _previewPlayerVC = [[JZPreviewPlayerController alloc] init];
    }
    return _previewPlayerVC;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

// 视频保存相册
- (void)saveToPhotoWithUrl:(NSURL *)url {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
    } completionHandler:nil];
}


@end


